//
//  AppDelegate.m
//  NiuBanJin
//
//  Created by Billy on 15/9/8.
//  Copyright (c) 2015年 zzjr. All rights reserved.
//

#import "AppDelegate.h"
#import "OnboardingViewController.h"
#import "OnboardingContentViewController.h"
#import "IQKeyboardManager.h"
#import "LoginViewController.h"
#import "CustomTabBarViewController.h"
#import "CLLockVC.h"
#import "RegisterViewController.h"
#import "CooridnatorController.h"


@interface AppDelegate ()

@property (nonatomic, strong) UIImageView *imageView_bg; //用来加载gif

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    [self loadRootViewController];
    
    [self.window makeKeyAndVisible];
    
    // 显示welome页面不显示动画
    NSString *launchTimes = [[NSUserDefaults standardUserDefaults] valueForKey:@"launch"];
    if ([launchTimes isEqualToString:@"1"]) {
    
        // 加载动画
        [self loadAnimation];
    }
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark - Custom code

- (void) loadAnimation {
    
    UIImageView *imageView_bg = [[UIImageView alloc] initWithFrame:self.window.frame];
    
    self.imageView_bg = imageView_bg;
    
    if (iPhone4) {
        
        [imageView_bg setImage:[UIImage imageNamed:@"bg4"]];
    } else if(iPhone5){
        
        [imageView_bg setImage:[UIImage imageNamed:@"bg5"]];
    }else if(iPhone6){
        
        [imageView_bg setImage:[UIImage imageNamed:@"bg6"]];
    }else if(iPhone6p) {
        
        [imageView_bg setImage:[UIImage imageNamed:@"bg6p"]];
    }
    
    [self.window addSubview:imageView_bg];
    
    UIImageView *imageView_tmp = [[UIImageView alloc] initWithFrame:self.window.frame];
    [imageView_tmp setFrame:CGRectMake(MULTIPLYWIDTH(228.0/2), MULTIPLYHEIGHT(700.0/2), MULTIPLYWIDTH(296.0/2), MULTIPLYHEIGHT(38.0/2))];
    [imageView_tmp setImage:[UIImage imageNamed:@"text"]];
    
    [imageView_bg addSubview:imageView_tmp];
    
    CAKeyframeAnimation* animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = 1.0;
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1, 1.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(369/296.0, 369/296.0, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    animation.values = values;
    [animation setDelegate:self];
    
    [imageView_tmp.layer addAnimation:animation forKey:nil];
}

- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag {
    
    [UIView animateWithDuration:0.8 animations:^{
        
        [self.imageView_bg setAlpha:0.0];
    } completion:^(BOOL finished) {
        
        [self.imageView_bg  removeFromSuperview];
    }];    
}

#pragma mark - Welcome Page info

- (OnboardingViewController *) welcomeViewControllerCreation {
    
    OnboardingContentViewController *firstPage = [OnboardingContentViewController
                                                  contentWithTitle:nil
                                                  body:nil
                                                  image:nil
                                                  buttonText:nil
                                                  action:nil];
    
    [firstPage.view.layer setContents:(__bridge id)[UIImage imageNamed:@"welcome1"].CGImage];
    
    OnboardingContentViewController *secondPage = [OnboardingContentViewController
                                                   contentWithTitle:nil
                                                   body:nil
                                                   image:nil
                                                   buttonText:nil
                                                   action:nil];
                                                   
    
     [secondPage.view.layer setContents:(__bridge id)[UIImage imageNamed:@"welcome2"].CGImage];
    
    OnboardingContentViewController *thirdPage = [OnboardingContentViewController
                                                  contentWithTitle:nil
                                                  body:nil
                                                  image:nil
                                                  buttonText:nil
                                                  action:nil];
    
    [thirdPage.view.layer setContents:(__bridge id)[UIImage imageNamed:@"welcome3"].CGImage];
    
    OnboardingContentViewController *forthPage = [OnboardingContentViewController
                                                  contentWithTitle:nil
                                                  body:nil
                                                  image:nil
                                                  buttonText:nil
                                                  action:nil];
    
    
    [forthPage.view.layer setContents:(__bridge id)[UIImage imageNamed:@"welcome4"].CGImage];
    
    
    //自定义button
    
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(142.0 * SCALE_RATE_WIDTH/2, SCREEN_HEIGHT -94 * SCALE_RATE_WIDTH -10*SCALE_RATE_HEIGHT, SCREEN_WIDTH - 142 * SCALE_RATE_WIDTH, 94.0/2)];
    [forthPage.view addSubview:button];
    
    [button.layer setCornerRadius:47/2.0];
    [button.layer setBorderColor:[UIColor whiteColor].CGColor];
    [button.layer setBorderWidth:1.0f];
    [button setTag:10];
    [button setTitle:@"立即体验" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(handleButtonPressed:) forControlEvents:UIControlEventTouchUpInside];

    OnboardingViewController *welcomeVC = [OnboardingViewController onboardWithBackgroundImage:[UIImage imageNamed:@"tree"] contents:@[firstPage,secondPage,thirdPage,forthPage]];

    CGFloat size = 90.0 ;
    CGFloat fontSize = 15.0;
    if (iPhone4) {
        
        size = 60.0;
        fontSize = 11.0 ;
    } else if (iPhone5) {
        
        fontSize = 13.0 ;
    }else if (iPhone6p) {
        
        
    }else {
        
    }
    
      // 自定义skip button
    for (OnboardingContentViewController *tmp in welcomeVC.viewControllers) {
    
        if (![tmp isEqual:welcomeVC.viewControllers.lastObject]) {
            
            UIButton *button_skip = [[UIButton alloc] initWithFrame:CGRectMake(tmp.view.frame.size.width-10*SCALE_RATE_WIDTH - size*SCALE_RATE_HEIGHT/2, SCREEN_HEIGHT - 10*SCALE_RATE_HEIGHT - size *SCALE_RATE_HEIGHT/2, size*SCALE_RATE_WIDTH/2, size*SCALE_RATE_HEIGHT/2)];
            [button_skip setTitle:@"跳过" forState:UIControlStateNormal];
            
            [button_skip.layer setCornerRadius:size*SCALE_RATE_HEIGHT/4];
            

            [button_skip.titleLabel setFont:[UIFont systemFontOfSize:fontSize]];
            [button_skip.layer setBorderColor:[UIColor whiteColor].CGColor];
            [button_skip.layer setBorderWidth:1.0f];
            [button_skip addTarget:self action:@selector(handleButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
            [button_skip setTag:11];
            [tmp.view addSubview:button_skip];
        }
    }

    return welcomeVC;
}

- (void) handleButtonPressed:(UIButton *) button {
    
    switch (button.tag) {
        case 10:
        {
            [[NSUserDefaults standardUserDefaults] setValue:@"1" forKey:@"launch"];
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:[LoginViewController new]];
            [self.window setRootViewController:nav];
        }
            break;
        case 11:
        {
            [[NSUserDefaults standardUserDefaults] setValue:@"1" forKey:@"launch"];
            
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:[LoginViewController new]];
            [self.window setRootViewController:nav];
        }
            break;
        default:
            break;
    }
}

- (void) loadRootViewController {

    // 读取存起来的user 如果有的话
    
    User *user_saved = [[UserManager sharedUserManager] getCurrentUser];
    
    [[UserManager sharedUserManager] setUser:user_saved];
    
        /** launchTimes:  利用该值来决定是否显示欢迎界面*/
        NSString *launchTimes = [[NSUserDefaults standardUserDefaults] valueForKey:@"launch"];
    
        if (![launchTimes isEqualToString:@"1"]) {
    
            // 第一次启动显示欢迎页面
            [self.window setRootViewController:[self welcomeViewControllerCreation]];
    
        } else { // 不是第一次，不显示welcome但是要显示动画
            
          // 检测是否登录过
    
            if ([self hasLogin]) {
                
                NSLog(@"用户已经登录!");
                
                self.window.rootViewController = [CooridnatorController new]; //11.6 优化
                
                //检测用户有没有禁用手势密码,默认是开
                //取用户的密码设置
                NSString *str_passwordEnabled = [[NSUserDefaults standardUserDefaults] valueForKey:@"gesturePasswordEnabled" ];
                
                if (!str_passwordEnabled) { //表明是第二次启动了默认是启动手势密码
                    
                 
                    [self loginUserCheckingLogic];
                }else  { //如果 str_passwordEnabled 不为空，表明用户已经设置过了
                    
                    if ([str_passwordEnabled isEqualToString:@"1"]) { //用户开了密码

                        [self loginUserCheckingLogic];
                         
                    }else { //用户关了密码
                        
                        // 直接显示主界面，不做操作
                        self.window.rootViewController = [CustomTabBarViewController new];
                    }
                }

            }else {
    
              NSLog(@"用户没有登录!");
                // 跳到登录框
                
                UINavigationController *nav_noLogin = [[UINavigationController alloc] initWithRootViewController:[LoginViewController new]];
                [self.window setRootViewController:nav_noLogin];
            }
        }
    
    // 键盘控制code
    [[IQKeyboardManager sharedManager] setEnable:YES];
    [[IQKeyboardManager sharedManager] setShouldResignOnTouchOutside:YES];
    [[IQKeyboardManager sharedManager] setShouldToolbarUsesTextFieldTintColor:YES];
    [[IQKeyboardManager sharedManager] setEnableAutoToolbar:NO];
    
}

#pragma mark - user login checking

- (void) loginUserCheckingLogic {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [CLLockVC showVerifyLockVCInVC:self.window.rootViewController forgetPwdBlock:^{
            
            // 跳到收验证码页面
            
            RegisterViewController *regsiterVC = [[RegisterViewController alloc] init];
            
            [regsiterVC setStr_type:@"retrievePassword"];
            [regsiterVC setStr_cellNumber:[UserManager sharedUserManager].user.user_userName];
            
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:regsiterVC];
            
            self.window.rootViewController = nav;
            
        } successBlock:^(CLLockVC *lockVC, NSString *pwd) {
            
            [MBProgressHUD showHUDAddedTo:lockVC.view animated:YES];
            // 和服务器验证密码
            NSDictionary *dic_paras = @{@"mobile":[UserManager sharedUserManager].user.user_userName,@"gesturePassword":pwd,@"udidStr":[UsefulUtil getUDIDOfCurrentDevice]};
            
            [[NetworkUtil sharedNetworkUtil] zzjrUserLoginByParmeteres:dic_paras transferResultUsingBlock:^(id parsedData, NSError *error) {
                
                [MBProgressHUD hideAllHUDsForView:lockVC.view animated:YES];
                if (!error) {  //没有网络错误
                    
                    // 开始解析数据
                    NSDictionary *dic = parsedData;
                    
                    if([dic[@"status"] intValue] == 0) {
                        
                        // 保存用户重要信息
                        
                        User *user = [[User alloc] initWithAttributes:dic[@"result"]];
                        [[UserManager sharedUserManager] setUser:user];
                        [[UserManager sharedUserManager] saveCurrentUser:user];
                        
                        [lockVC dismiss:0];
                        CURRENT_WINDOW.rootViewController = [CustomTabBarViewController new];
                    } else {// 不是网络出错，是密码错 or 其它错误
                        
                        [MBProgressHUD hideAllHUDsForView:lockVC.view animated:YES];
                        
                        [lockVC.view setUserInteractionEnabled:YES];
                        [self loadRootViewController];  //重试一直到成功
                        
                        [UsefulUtil showAlertView:dic[@"msg"]];
                    }
                }else {
                    
                    [MBProgressHUD hideAllHUDsForView:lockVC.view animated:YES];
                    [lockVC.view setUserInteractionEnabled:YES];
                    [self loadRootViewController];  //重试一直到成功
                    [UsefulUtil showAlertView:error.description];
                }
                
            }];
            
        }];
    });

}
- (BOOL) hasLogin {
    
    return  [[UserManager sharedUserManager] isLogin];
}

@end
